package com.auto.learning.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.client.ClientProtocolException;

import android.content.Context;

import com.auto.learning.bean.VersionInfo;
import com.auto.learning.event.EventBus;
import com.auto.learning.net.DownLoadHelper;
import com.auto.learning.net.DownLoadInfo;

public class DownLoadAppThread extends Thread{
	private Context context;
	private String fileName = "tempApk.apk";
	private final int BUFFER_SIZE = 16 * 1024;
	private VersionInfo info;
	public DownLoadAppThread(Context context, VersionInfo info){
		this.context = context;
		this.info = info;
	}
	
	public DownLoadAppThread(){
		
	}
	
	@Override
	public void run() {
		try {
			String filePath = FileUtil.getFileCachePath()+"/"+DownLoadInfo.APK_CACHE_PATH+"/"+fileName ;
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			InputStream in = DownLoadHelper.getFileInputStream(context, info.apkUrl);
			OutputStream out = new FileOutputStream(filePath);
			in = new BufferedInputStream(in, BUFFER_SIZE);
			out = new BufferedOutputStream(out, BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len;
			int loadedLength = 0;
			while ((len = in.read(buffer, 0, BUFFER_SIZE)) > 0) {
				out.write(buffer, 0, len);
				loadedLength += len;
				if (loadedLength == info.apkSize) {
					EventBus.getEventBus("install_apk").post(filePath);
				}
			}
			out.flush();
			if (null != in) {
				in.close();
			}
			if (null != out) {
				out.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
